<template>
  <div class="container-uploadImage">
    <el-upload
      class="avatar-uploader"
      ref="upload"
      action="fakeaction"
      :show-file-list="false"
      :http-request="uploadSectionFile"
      :on-success="uploadImgSuccess"
    >
        <img v-if="image" :src="image" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</div>
</template>

<script>
// import { getItem } from '../utils/storage'
export default {
  data () {
    return {
      image: '',
      listData: [],
      imageUrl: ''
    }
  },
  methods: {
    async uploadSectionFile (params) {
      this.imageUrl = params.file
      const file = params.file
      const fileType = file.type
      const isImage = fileType.indexOf('image') !== -1
      const isLt2M = file.size / 1024 / 1024 < 2
      // 这里常规检验，看项目需求而定
      if (!isImage) {
        this.$message.error('只能上传图片格式png、jpg、gif!')
        return
      }
      if (!isLt2M) {
        this.$message.error('只能上传图片大小小于2M')
        return
      }
      const formData = new FormData()
      formData.append('files', file)
      if (this.$route.path === '/setting') {
        formData.append('type', 2)
      } else if (this.$route.path === '/company') {
        formData.append('type', 1)
      }
      const res = await this.$http({
        url: '/api/platApi/system/option/upLoadImg',
        method: 'post',
        data: formData,
        headers: { 'content-type': 'multipart/form-data' }
      })
      if (res.status === 200 && res.data.code === 1) {
        this.imageUrl = res.data.data
      }
    },
    uploadImgSuccess (res, file) {
      this.image = URL.createObjectURL(file.raw)
      if (this.$route.path === '/setting') {
        this.$emit('updateImageUrl', this.imageUrl)
      } else if (this.$route.path === '/company') {
        this.$emit('updateCompanyImageUrl', this.imageUrl)
      }
    }
  }

}
</script>

<style scoped lang="less">
 /deep/.avatar-uploader .el-upload {
    border: 1px dashed #363434;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    margin-left: 10%;
  }
  /deep/.avatar-uploader /deep/.el-upload:hover {
    border-color: #409EFF;
  }
  /deep/.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  /deep/.avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
